package com.lynn.salary.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;

import com.lynn.salary.dao.ICommonDao;

public class MyInvocationHandler implements InvocationHandler {
	private Object target = null;

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		if ((target.getClass().getName().contains("dao"))) {
			return invokeDao(proxy, method, args);
		}

		Connection conn = DBUtil.getConnection();
		BeansInterface bi = (BeansInterface) target;
		bi.setConnection(conn);
		ICommonDao dao = (ICommonDao) ObjectFactory.getTarget("dao");
		bi.setDao(dao);
		dao.setConnection(conn);
		Object returnValue = null;
		try {
			returnValue = method.invoke(target, args);

			if (target.getClass().getName().toUpperCase().contains("SERVICE")) {
				conn.commit();
				System.out.println(target.getClass().getName() + " ==> " + method.getName() + " completed....");
			}

			conn.close();
		} catch (Exception e) {
			System.err.println("MyInvocationHandler::invoke .... ERROR");
			System.err.println("MyInvocationHandler::invoke 回滚事务");
			conn.rollback();
			conn.close();
//			e.printStackTrace();
			throw e;
		}

		return returnValue;
	}

	public Object invokeDao(Object proxy, Method method, Object[] args) throws Throwable {
		ICommonDao dao = (ICommonDao) target;
		Connection conn = DBUtil.getConnection();
		dao.setConnection(conn);
		Object o = null;
		try {
			o = method.invoke(dao, args);
			conn.close();
		} catch (Exception e) {
			conn.rollback();
			conn.close();
			e.printStackTrace();
			throw e;
		}
		return o;
	}

	public Object getTarget() {
		return target;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

}
